package com.seven.first.suite.util;
import java.math.BigInteger;

public class RadixCode {
 
	private final static BigInteger scale = new BigInteger("128");
	
	public static String encode(BigInteger val ) {
		BigInteger num = new BigInteger(val.toString()); 
		StringBuilder sb = new StringBuilder();
		int remainder = 0;

		while ( num.compareTo(scale.multiply(BigInteger.ONE)) > 0) {
			/**
			 * 对 scale 进行求余，然后将余数追加至 sb 中，由于是从末位开始追加的，因此最后需要反转（reverse）字符串
			 */
			remainder = num.remainder(scale).intValue();
			sb.append(getChar(remainder));

			num = num.divide(scale);
		}

		sb.append(getChar(num.intValue()) );
		String value = sb.reverse().toString();
		return value;
	}
	public static BigInteger decode(String str ) {
		/**
		 * 将 0 开头的字符串进行替换
		 */
		str = str.replace("^0*", "");
		BigInteger num = BigInteger.ZERO;
		int index = 0;
		int len = str.length() - 1;
		for (int i = 0; i < str.length(); i++) {
			/**
			 * 查找字符的索引位置
			 */
			index = getIndex(str.charAt(i));
			/**
			 * 索引位置代表字符的数值
			 */
			int mylen = len - i;
			BigInteger pow = scale.pow(mylen);
			BigInteger t = BigInteger.valueOf(index).multiply(pow);
			num = num.add(t); 
		}

		return num;
	}
	private static char getChar(int index) {
		return (char)index;
	}
	private static int getIndex(char a) {
		return (int)a;
	}
	
	 
//
//	public static void main(String[] args) {  
//		BigInteger bb = new BigInteger("0");
//		for ( int i = 0 ; i < 5000 ; i ++) {
//			bb = bb.setBit(i);
//		}
//		 
//		
//		
//		
//		
// 
//		System.out.println(bb);
//		System.out.println(bb.toString().length());
//		System.out.println(RadixCode.encode(bb));
//		System.out.println(RadixCode.encode(bb).length());
//
//		//System.out.println(RadixCode.decode(RadixCode.encode(bb)));
//
//				
//		System.out.println(GzipUtil.zip(bb.toString()));
//		System.out.println(GzipUtil.zip(bb.toString()).length());
//				
//		String zip = GzipUtil.zip(RadixCode.encode(bb));
//		System.out.println(zip);
//		System.out.println(zip.length());
//		
//		String unzip = GzipUtil.unzip(zip);
//		System.out.println(unzip);
//		
//		System.out.println(RadixCode.decode(unzip));
//
//	}
}
